package com.recruit.wechat.utils;

import java.awt.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;

import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.apache.commons.lang.StringUtils;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 * @author josnow
 * @date 2017年5月9日 下午12:38:39
 * @version 1.0.0
 * @desc openoffice转换工具
 */
public class OpenOfficeUtils {

    public static final String LOCAL_HOST = "localhost";
    public static final int LOCAL_PORT = 8100;

    // Format
    public static DocumentFormatRegistry formatFactory = new DefaultDocumentFormatRegistry();

    /**
     *
     * @desc
     * @auth josnow
     * @date 2017年6月9日 下午4:11:04
     * @param inputFilePath
     *            待转换的文件路径
     * @param outputFilePath
     *            输出文件路径
     */
    public static void convert(String inputFilePath, String outputFilePath) throws ConnectException {
        convert(inputFilePath, outputFilePath, LOCAL_HOST, LOCAL_PORT);
    }

    /**
     *
     * @desc
     * @auth josnow
     * @date 2017年6月9日 下午4:12:29
     * @param inputFilePath
     *            待转换的文件路径
     * @param outputFilePath
     *            输出文件路径
     * @param connectIp
     *            远程调用ip
     * @param connectPort
     *            远程调用端口
     */
    public static void convert(String inputFilePath, String outputFilePath, String connectIp, int connectPort)
            throws ConnectException {
        if (StringUtils.isEmpty(inputFilePath) || StringUtils.isEmpty(outputFilePath)
                || StringUtils.isEmpty(connectIp)) {
            throw new IllegalArgumentException("参数异常！！");
        }
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(connectIp, connectPort);
        connection.connect();

// 		  TODO Excel转成PDF默认是A4纸
//        DocumentConverter converter = getConverter(connectIp, connection);
//        converter.convert(new File(inputFilePath), new File(outputFilePath));

// 		  TODO Excel转成PDF默认是A4纸， 如果现实折行，则自定义ConverterDocument，改变纸张大小
        ConverterDocument converterDocument = new ConverterDocument(connection);
        converterDocument.convert(new File(inputFilePath), new File(outputFilePath));

        connection.disconnect();
    }

    /**
     *
     * @desc
     * @auth josnow
     * @date 2017年6月9日 下午4:08:26
     * @param inputStream
     * @param inputFileExtension
     *            待转换文件的扩展名，例如: xls，doc
     * @param outputStream
     * @param outputFileExtension
     *            输出文件扩展名，例如：pdf
     */
    public static void convert(InputStream inputStream, String inputFileExtension, OutputStream outputStream,
                               String outputFileExtension) throws ConnectException {
        convert(inputStream, inputFileExtension, outputStream, outputFileExtension, LOCAL_HOST, LOCAL_PORT);
    }

    /**
     *
     * @desc
     * @auth josnow
     * @date 2017年6月9日 下午4:10:21
     * @param inputStream
     * @param inputFileExtension
     *            待转换文件的扩展名，例如: xls，doc
     * @param outputStream
     * @param outputFileExtension
     *            输出文件扩展名，例如：pdf
     * @param connectIp
     *            远程调用ip
     * @param connectPort
     *            远程调用端口
     */
    public static void convert(InputStream inputStream, String inputFileExtension, OutputStream outputStream,
                               String outputFileExtension, String connectIp, int connectPort) throws ConnectException {

        if (inputStream == null || StringUtils.isEmpty(inputFileExtension) || outputStream == null
                || StringUtils.isEmpty(outputFileExtension) || StringUtils.isEmpty(connectIp)) {
            throw new IllegalArgumentException("参数异常！！");
        }

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(connectIp, connectPort);
        connection.connect();
        DocumentConverter converter = getConverter(connectIp, connection);

        converter.convert(inputStream, formatFactory.getFormatByFileExtension(inputFileExtension), outputStream,
                formatFactory.getFormatByFileExtension(outputFileExtension));
        connection.disconnect();
    }

    private static DocumentConverter getConverter(String connectIp, OpenOfficeConnection connection) {
        DocumentConverter converter = "localhost".equals(connectIp) || "127.0.0.1".equals(connectIp)
                || "0:0:0:0:0:0:0:1".equals(connectIp) ? new OpenOfficeDocumentConverter(connection)
                : new StreamOpenOfficeDocumentConverter(connection);
        return converter;
    }

    public static void main(String[] args) throws Exception {
       OpenOfficeUtils.convert("C:\\Users\\xiao1993\\Desktop\\资料笔记\\简历\\jsd1905z2017肖守凯java一年", "C:\\Users\\xiao1993\\Desktop\\资料笔记\\简历\\jsd1905z2017肖守凯java一年.pdf");
//        pdf2image(new File("D:\\test.pdf"));
       // pdf2image(new File("C:\\Users\\xiao1993\\Desktop\\资料笔记\\简历\\xiaoshoukai.pdf"));

    }

    /**
     * pdf to big image
     * github: https://github.com/mmtou/pdf2img
     * @param pdfFile pdf文件路径
     * @return big image file
     * @throws Exception
     */
    public static File pdf2image(File pdfFile) throws Exception {

        // 拼成图片后的宽度和高度
        int w = 0;
        int h = 0;
        List<BufferedImage> images = new ArrayList();
        // 生成图片后的路径
        String path = pdfFile.getParent() + File.separator;
        System.out.println("图片路径:"+path);
        String fileName = pdfFile.getName().replace(".pdf", "");

        File destinationFile = new File(path);
        if (!destinationFile.exists()) {
            destinationFile.mkdir();
        }
        PDDocument document = PDDocument.load(pdfFile);
        PDPageTree list = document.getDocumentCatalog().getPages();
        int pageCounter = 0;
        for (PDPage page : list) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            BufferedImage image = pdfRenderer.renderImageWithDPI(pageCounter, 100, ImageType.RGB);
            String target = path + fileName + "-" + (pageCounter++) + ".png";
            System.out.println("target:"+target);
            ImageIOUtil.writeImage(image, target, 100);

            w = image.getWidth();
            h += image.getHeight();
            images.add(image);
            new File(target).delete();
        }
        document.close();

        BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics g = combined.getGraphics();

        int y = 0;
        for (BufferedImage image : images) {
            g.drawImage(image, 0, y, null);
            y += image.getHeight();
        }

        // Save as new image
        File image = new File(path, fileName + ".png");
        ImageIO.write(combined, "PNG", image);
        return image;
    }


}